package vip.aster.generator.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import vip.aster.common.utils.PageInfo;
import vip.aster.generator.config.DataSourceConfig;
import vip.aster.generator.config.DbType;
import vip.aster.generator.entity.GenDataSource;
import vip.aster.generator.mapper.GenDataSourceMapper;
import vip.aster.generator.query.Query;
import vip.aster.generator.service.GenDataSourceService;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

/**
 * GenDataSourceServiceImpl
 *
 * @author Aster
 * @since 2024/2/26 10:40
 */
@Service
@AllArgsConstructor
public class GenDataSourceServiceImpl extends ServiceImpl<GenDataSourceMapper, GenDataSource> implements GenDataSourceService {
    private final GenDataSourceMapper genDataSourceMapper;
    private final DataSource dataSource;

    @Override
    public PageInfo<GenDataSource> page(Query query) {
        LambdaQueryWrapper<GenDataSource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(query.getConnName()), GenDataSource::getConnName, query.getConnName());
        queryWrapper.eq(StrUtil.isNotBlank(query.getDbType()), GenDataSource::getDbType, query.getDbType());

        Page<GenDataSource> page = new Page<>(query.getPageNum(), query.getPageSize());
        Page<GenDataSource> pageList = genDataSourceMapper.selectPage(page, queryWrapper);

        return new PageInfo<>(pageList.getRecords(), pageList.getTotal());
    }

    @Override
    public List<GenDataSource> getList() {
        return genDataSourceMapper.selectList(Wrappers.emptyWrapper());
    }

    @Override
    public String getDatabaseProductName(String dataSourceId) {
        if (StrUtil.isBlank(dataSourceId)) {
            return DbType.MySQL.name();
        } else {
            return this.getById(dataSourceId).getDbType();
        }
    }

    @Override
    public DataSourceConfig get(String datasourceId) {
        // 初始化配置信息
        DataSourceConfig info = null;
        if (StrUtil.isBlank(datasourceId) || "0".equals(datasourceId)) {
            try {
                info = new DataSourceConfig(dataSource.getConnection());
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        } else {
            info = new DataSourceConfig(this.getById(datasourceId));
        }

        return info;
    }

    @Override
    public void saveDataSource(GenDataSource entity) {
        if (StrUtil.isNotBlank(entity.getId())) {
            genDataSourceMapper.updateById(entity);
        } else {
            genDataSourceMapper.insert(entity);
        }
    }
}
